package com.loiot.commons.zookeeper.lock;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;

public class DistributedLock implements Lock {

    private WriteLock lock;
    private String lockDir;
    private ZooKeeper zooKeeper;

    public DistributedLock(ZooKeeper zooKeeper, String lockDir, List<ACL> acl) {
        this.zooKeeper = zooKeeper;
        this.lockDir = lockDir;
    }

    @Override
    public void lock() {
        lock = new WriteLock(zooKeeper, lockDir, null);
        try {
            while (true) {
                if (lock.lock()) {
                    return;
                }
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void unlock() {
        lock.unlock();
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public Condition newCondition() {
        return null;
    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }
}
